import { _decorator, Component, EffectAsset, Material, MeshRenderer, Texture2D } from 'cc';
import { EDITOR } from 'cc/env';
const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('PlaneRender')
@executeInEditMode
export class PlaneRender extends Component {
    //状态
    @property({ type: Texture2D })
    _texture: Texture2D = null;

    //通过属性面板控制
    @property({ type: Texture2D })
    get texture(): Texture2D {
        return this._texture;
    }
    set texture(value) {
        this._texture = value;
        this.setProperty();
    }

    //状态
    @property({ type: EffectAsset })
    _effect: EffectAsset = null;

    //通过属性面板控制
    @property({ type: EffectAsset })
    get effect(): EffectAsset {
        return this._effect;
    }
    set effect(value) {
        this._effect = value;
        this.setMaterial();
        this.setProperty();
    }

    private setMaterial() {
        const material = new Material();
        if (EDITOR) {
            material.initialize({
                effectAsset: this._effect,
                defines: {
                    USE_ALBEDO_MAP: true,
                    USE_CURVED: false
                }
            });
        } else {
            material.initialize({
                effectAsset: this._effect,
                defines: {
                    USE_ALBEDO_MAP: true,
                    USE_CURVED: true
                }
            });
        }

        this.getComponent(MeshRenderer).setSharedMaterial(material, 0);
    }

    private setProperty() {
        const finalMat = this.getComponent(MeshRenderer).getSharedMaterial(0);
        if (finalMat) {
            finalMat.setProperty("albedoMap", this.texture);
            finalMat.setProperty("_CurvedFactorDepth", this.depth);
            finalMat.setProperty("_CurvedFactorSmooth", this.smooth);
            finalMat.setProperty("_CurvedFactorStrength", this.strength);
        }

    }

    @property
    private depth: number = 47;
    @property
    private smooth: number = 2.75;
    @property
    private strength: number = 0.01;

    protected onLoad(): void {
        this.setMaterial();
        this.setProperty();
    }

}


